package com.mynews.activities.mynews;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.adapter.NewsAdapter;
import com.mynews.bean.NewsBean;
import com.mynews.databinding.ActivityMyNewsBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MyNewsVM extends AndroidViewModel {
    private final List<NewsBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static ActivityMyNewsBinding binding;
    @SuppressLint("StaticFieldLeak")
    private static MyNewsActivity myNewsActivity;
    public MyNewsVM(@NonNull Application application) { super(application); }
    public void setBinding(ActivityMyNewsBinding binding, MyNewsActivity myNewsActivity) {
        binding.setAdp(new NewsAdapter(myNewsActivity,data));
        MyNewsVM.binding=binding;
        MyNewsVM.myNewsActivity=myNewsActivity;
        binding.mynewsList.setOnItemClickListener((parent, view, position, id) -> {
            App.newsBean=data.get(position);
            myNewsActivity.startActivity(new Intent(myNewsActivity, DetailActivity.class));
        });
        binding.mynewsList.setOnItemLongClickListener((parent, view, position, id) -> {
            AlertDialog.Builder dialog=new AlertDialog.Builder(myNewsActivity);
            dialog.setTitle("提示").setMessage("是否删除？").setPositiveButton("确定", (dialog1, which) -> {
                BmobApi.delete("https://api2.bmob.cn/1/classes/news/"+data.get(position).id, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        //删除评论回复点赞收藏,举报不能删除，要显示该举报新闻已删除
                        refresh();
                    }
                });
                deleteTable("reply", data.get(position).id);
                deleteTable("comment", data.get(position).id);
                deleteTable("like", data.get(position).id);
                deleteTable("collection", data.get(position).id);
            }).setNeutralButton("取消",null).show();
            return true;
        });
        refresh();
    }
    private void deleteTable(String tableName, String value) {
        BmobApi.get("https://api2.bmob.cn/1/classes/"+tableName+"?where="+ URLEncoder.encode("{\""+ "newsId" +"\":\""+value+"\"}"), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        BmobApi.delete("https://api2.bmob.cn/1/classes/"+tableName+"/"+ja.getJSONObject(i).getString("objectId"), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) { }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
    private void refresh() {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/news?where={\"ownerId\":\""+ App.user.objectId+"\"}", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja  = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo=ja.getJSONObject(i);
                        data.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),App.user));
                    }
                    myNewsActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}